import type { VbenFormSchema } from '#/adapter/form'

import type { Ref } from 'vue'
import { computed, nextTick, watch } from 'vue'

import { CurrentCountryLanguageOptions } from '#/config/options/locales'
import type { ExtendedFormApi } from '@vben/common-ui'
import { z } from '@vben/common-ui'
import { $t } from '@vben/locales'
import { isEmpty } from '@vben/utils'

export function getAddEditFormSchema(opts?: {
    formApi?: ExtendedFormApi
    rowId: Ref<null | number>
    tableData?: any[]
}) {
    const { rowId, formApi, tableData } = opts || {}
    const isEdit = computed(() => !isEmpty(rowId?.value))
    // 不能编辑code 否则导致前端ui显示错误
    watch(
        isEdit,
        (val) => {
            if (opts?.formApi) {
                nextTick(() => {
                    formApi?.updateSchema([
                        {
                            fieldName: 'code',
                            componentProps: {
                                disabled: val
                            }
                        }
                    ])
                })
            }
        },
        {
            immediate: true
        }
    )
    return [
        {
            fieldName: 'code',
            label: $t('page.system.children.dictionarySub.children.form.language'),
            defaultValue: '',
            component: 'Select',
            componentProps: {
                class: 'w-full',
                options: CurrentCountryLanguageOptions
            },
            rules: 'required',
            dependencies: {
                triggerFields: ['code'],
                rules: (values) => {
                    return z
                        .string()
                        .min(1)
                        .refine(
                            () => {
                                const isExist = tableData?.some((item) => item.code === values.code)
                                const oldVal = isEdit.value
                                    ? tableData?.find((v) => v.id === rowId?.value)?.code
                                    : ''
                                return values.code === oldVal || !isExist
                            },
                            {
                                message: $t('common.isExist')
                            }
                        )
                }
            }
        },
        {
            fieldName: 'name',
            defaultValue: '',
            label: $t('page.system.children.dictionarySub.children.form.name'),
            component: 'Input',
            rules: 'required'
        },

        {
            fieldName: 'note',
            label: $t('common.remark'),
            component: 'Input',
            defaultValue: ''
        }
    ] as VbenFormSchema[]
}
